package org.etl.kfrwe.service;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.etl.kfrwe.bean.BaseDirectory;
import org.etl.kfrwe.bean.FileRepository;
import org.etl.kfrwe.common.RunningJobs;
import org.etl.kfrwe.common.RunningTransformations;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

@Service("fileRepositoryService")
public class FileRepositoryServiceImpl implements FileRepositoryService {

    @Override
    public List<FileRepository> selectList() {
        /**
         * 1、获取当前OS
         * 2、如果为win，获取当前系统用户名称
         * 3、构造文件资源库配置文件路径
         * 4、解析配置文件，封装为实体
         * 5、返回结果集
         */
        Properties props = System.getProperties();
        String OSName = props.getProperty("os.name");
        if (OSName.indexOf("Windows") != -1) {
            // Windows
            String userHome = props.getProperty("user.home");
            String repositoriesPath = userHome + "\\.kettle\\repositories.xml";
            return parseRepositoriesConfFile(repositoriesPath);
        } else {
            // Linux
        }
        return null;
    }

    @Override
    public List<String> jobAndTranSelectList(String path) {
        return readJobAndTrans(path);
    }

    @Override
    public String runningTrans(String repositoryName, String directory, String transName, String username, String password) {
        return RunningTransformations.running(repositoryName, directory, transName, username, password);
    }

    @Override
    public String running(String repositoryName, String directory, String name, String username, String password) {
        String logText = "";
        // 判断是trans，还是job
        if (name.indexOf(".ktr") != -1) {
            String transName = name.replace(".ktr", "");
            logText = RunningTransformations.running(repositoryName, directory, transName, username, password);
        } else {
            String jobName = name.replace(".kjb", "");
            logText = RunningJobs.running(repositoryName, directory, jobName, username, password);
        }
        return logText;
    }

    @Override
    public String viewbox(String resourcePath) {
        File file = new File(resourcePath);
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            String tempStr = null;
            while ((tempStr = bufferedReader.readLine()) != null) {
                stringBuilder.append(tempStr);
                stringBuilder.append(System.getProperty("line.separator"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    /**
     * 读取工作和转换
     * @param path
     * @return
     */
    private List<String> readJobAndTrans(String path) {
        List<String> list = new ArrayList<>();
        File jobAndTransPathFile = new File(path);
        if (jobAndTransPathFile.exists()) {
            File[] files = jobAndTransPathFile.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().indexOf(".ktr")!=-1||pathname.getName().indexOf(".kjb")!=-1;
                }
            });
            for (File file : files) {
                list.add(file.getPath());
            }
        }
        return list;
    }

    /**
     * 解析资源库配置文件
     * @param repositoriesPath
     * @return
     */
    private List<FileRepository> parseRepositoriesConfFile(String repositoriesPath) {
        List<FileRepository> list = new ArrayList<>();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(repositoriesPath));
            Element element = document.getRootElement();
            Iterator iterator = element.elementIterator();
            while (iterator.hasNext()) {
                FileRepository fileRepository = new FileRepository();
                Element fileRepositoryElement = (Element) iterator.next();
                Iterator fileRepositoryIterator = fileRepositoryElement.elementIterator();

                while (fileRepositoryIterator.hasNext()) {
                    Element child = (Element) fileRepositoryIterator.next();
                    String nodeName = child.getName();
                    if (nodeName.equals("id")) {
                        fileRepository.setId(child.getStringValue());
                    } else if (nodeName.equals("name")) {
                        fileRepository.setName(child.getStringValue());
                    } else if (nodeName.equals("description")) {
                        fileRepository.setDescription(child.getStringValue());
                    } else if (nodeName.equals("base_directory")) {
                        String baseDirectory = child.getStringValue();
                        fileRepository.setBaseDirectory(baseDirectory);
                        // 解析资源库配置基础目录
                        List<BaseDirectory> baseDirectoryList = parseRepositoriesBaseDirectory(baseDirectory);
                        fileRepository.setChildren(baseDirectoryList);
                    } else if (nodeName.equals("read_only")) {
                        fileRepository.setReadOnly(child.getStringValue());
                    } else if (nodeName.equals("hides_hidden_files")) {
                        fileRepository.setHidesHiddenFiles(child.getStringValue());
                    }
                }



                list.add(fileRepository);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 解析资源库配置基础目录
     * @param baseDirectoryPath
     * @return
     */
    private List<BaseDirectory> parseRepositoriesBaseDirectory(String baseDirectoryPath) {
        List<BaseDirectory> list = new ArrayList<>();
        File baseDirectoryPathFile = new File(baseDirectoryPath);
        if (baseDirectoryPathFile.exists()) {
            File[] files = baseDirectoryPathFile.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return !pathname.getName().equals(".meta");
                }
            });
            for (File file : files) {
                if (file.isDirectory()) {
                    BaseDirectory baseDirectory = new BaseDirectory();
                    baseDirectory.setName(file.getName());
                    baseDirectory.setPath(file.getPath());
                    parseRepositoriesBaseDirectory(baseDirectory, file.getPath());
                    list.add(baseDirectory);
                }
            }
        }
        return list;
    }

    private List<BaseDirectory> parseRepositoriesBaseDirectory(BaseDirectory baseDirectory, String baseDirectoryPath) {
        List<BaseDirectory> list = new ArrayList<>();
        File baseDirectoryPathFile = new File(baseDirectoryPath);
        if (baseDirectoryPathFile.exists()) {
            File[] files = baseDirectoryPathFile.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    BaseDirectory baseDirectory1 = new BaseDirectory();
                    baseDirectory1.setName(file.getName());
                    baseDirectory1.setPath(file.getPath());
                    parseRepositoriesBaseDirectory(baseDirectory1, file.getPath());
                    list.add(baseDirectory1);
                }
            }
            if (list.size() != 0) baseDirectory.setIsParent(true);
            baseDirectory.setChildren(list);
        }
        return list;
    }

    public static void main(String[] args) {
        FileRepositoryServiceImpl FileRepositoryServiceImpl = new FileRepositoryServiceImpl();
        FileRepositoryServiceImpl.parseRepositoriesBaseDirectory("D:\\workspace\\HZZHJG_Code\\ZHJG_Code\\hzzj\\sql\\11-sjjh\\hzjg_src");
    }
}
